<template>
    <div class="mapedit">
        <vHeadSpace />
        <div class="topoContent">
            <vAsideSpace />
            <el-main class="mapedit-main">
                <div class="map-left-content">
                    <!-- 主内容-上部分  -->
                    <div class="left_head">
                        <!-- 主内容-上部分-标题栏(界面调整暂时隐藏)  -->
<!--                        <div class="left_head_title">-->
<!--                            <h3 style="margin:0">当前机房:{{this.engineRoomDetails.currentEngineRoom}}-当前机柜:{{this.engineRoomDetails.currentCabinet}}</h3>-->
<!--                        </div>-->
                        <!-- 主内容-上部分-视图切换栏  -->
                        <div class="left-head-views">
<!--                            <el-button style="margin-top: 2px" type="success" size="small">运行视图</el-button>-->
<!--                            <el-button style="margin-left: 10px;margin-top: 2px" type="primary" size="small">业务视图</el-button>-->
<!--                            <el-button style="margin-left: 10px;margin-top: 2px" type="warning" size="small">告警视图</el-button>-->
                            <el-tabs v-model="activeName" @tab-click="handleClick">
                                <el-tab-pane style="padding-left: 20px" label="运行视图" name="first" ></el-tab-pane>
                                <el-tab-pane label="业务视图" name="second"></el-tab-pane>
                                <el-tab-pane label="告警视图" name="third"></el-tab-pane>
                            </el-tabs>
                        </div>
                        <!-- 主内容-上部分-工具栏  -->
                        <div class="left_head_tool">
                            <el-button size="medium" type="text" style="margin-left:10px;" @click="createNode">创建</el-button>
                            <el-button type="text" style="margin-left:10px;" @click="deleteChooseNode">删除</el-button>

                            <span style="color: white;margin-left: 10px">&nbsp;网格：
                                <el-button size="medium" type="text" v-text="isGridShow?'显示':'隐藏'" @click="isGridShow=!isGridShow" >显示</el-button>
                            </span>

                            <span style="color: white;margin-left: 10px">连线:&nbsp;
                              <el-button size="medium" type="text" @click="createLink" style="margin: 0 5px">添加</el-button>
                            </span>

                            <span style="color: white;margin-left: 10px">鼠标：
                                <el-radio-group v-model="radioMode" >
                                    <el-radio label="select" style="margin-right: 10px;margin-bottom: 0;margin-top: 9px">选择</el-radio>
                                    <el-radio label="drag" style="margin-right: 10px">拖动</el-radio>&nbsp;&nbsp;
                                </el-radio-group>
                            </span>

                          <el-button size="small" @click = "chooseEngines">物理机划入</el-button>
                          <el-button size="small" style="margin:10px" @click = "topoInitCreate">拓扑初始化</el-button>
                          <el-button size="small" style="margin:10px" @click = "saveTopu">保存</el-button>
                          <el-button size="small" style="margin:10px" @click = "paintTopoMapBySysmapids('15')">get</el-button>
                          <el-button size="small" type="danger" style="margin:10px" @click = "redBoom">红色爆炸</el-button>
                        </div>
                    </div>
                    <!-- 主内容-下部分  -->
                    <div class="map_body">
                        <!-- 主内容-下部分-左边拓扑图内容  -->
                        <div v-show="showNumber == 1" class="map_body_left">
                            <canvas @drop="drop($event)" @dragover="allowDrop($event)" id="canvas" :width="canvasWidth" :height="canvasHeight" style="border:1px solid #DFE4EA;float: left" :class="isGridShow?'mapCanvas-content':'noGrid'"></canvas>
                        </div>
                        <div v-show="showNumber == 2" class="map_body_left">
                                这是业务视图
<!--                            <canvas id="canvas_two" :width="canvasWidth" :height="canvasHeight" style="border:1px solid #DFE4EA;float: left" :class="isGridShow?'mapCanvas-content':'noGrid'"></canvas>-->
                        </div>
                        <div v-show="showNumber == 3" class="map_body_left">
                                这是告警视图
<!--                            <canvas id="canvas_three" :width="canvasWidth" :height="canvasHeight" style="border:1px solid #DFE4EA;float: left" :class="isGridShow?'mapCanvas-content':'noGrid'"></canvas>-->
                        </div>

                        <!-- 主内容-下部分-更左边机房机柜展示列表  -->
                        <div class="map-body-lefter-room">
                            <div class="right_menu">
<!--                              <TopoMenuOne></TopoMenuOne>-->
                              <TopoMenu></TopoMenu>
                            </div>
<!--                            <el-button size="small" @click = "chooseEngines">物理机划入</el-button>-->
<!--                            <el-button size="small" style="margin:0" @click = "topoInitCreate">拓扑初始化</el-button>-->
<!--                            <router-link :to="{name:'HostMap', query: {}}">-->
<!--                                <el-button size="small">之前</el-button>-->
<!--                            </router-link>-->
<!--                            <el-button size="small" style="margin:0" @click = "saveTopu">保存</el-button>-->
<!--                            <el-button size="small" style="margin:0" @click = "paintTopoMapBySysmapids('12')">get</el-button>-->

<!--                            <el-button type="text" size="small" icon="el-icon-edit" @click="elementChooseChange" style="background-color: #133b5c;width: 100%;color:white">文字添加</el-button>-->
<!--                            <el-button type="text" size="small" icon="el-icon-s-platform" @click="elementChooseChange" style="background-color: #133b5c;width: 100%;margin-left: 0;margin-top: 1px;color:white">设备添加</el-button>-->
<!--                            <el-divider class="el_divider"></el-divider>-->
<!--                            <div v-show="hostElementVisable" style="width: 100%;">-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/switch.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">交换机</span>-->
<!--                                </div>-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/host.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">服务器</span>-->
<!--                                </div>-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/firewall.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">防火墙</span>-->
<!--                                </div>-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/wangza.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">单向网闸</span>-->
<!--                                </div>-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/router.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">路由器</span>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                            <div v-show="wordElementVisable" style="width: 100%;">-->
<!--                                <div class="divelement" style="margin: 6px 0" draggable="true" @dragstart="dragStart($event)">-->
<!--                                    <img width="24" height="18" style="margin-left: 4px" draggable="false" src="../../../public/img/topo/picture.png"/>-->
<!--                                    <span style="font-size: 12px;margin-left: 4px;cursor: move">文字</span>-->
<!--                                </div>-->
<!--                            </div>-->
                        </div>
                    </div>
                </div>
                <div class="map-left-content-bottom">
                    <vFootSpace />
                </div>
            </el-main>
        </div>

        <!-- 编辑节点弹框-->
        <div class="editNodeForm">
            <el-dialog title="地图元素" :visible.sync="isEditFormShow" width="1000px" height="500px">
                <el-form :model="formData" ref="formData"  label-width="100px">
                    <el-row>
                        <el-col>
                            <el-form-item label="设备类型" prop="type">
                                <el-select v-model="formData.type" placeholder="请选择" style="width: 200px" >
                                    <el-option label="主机" :value="1" ></el-option>
                                    <el-option label="交换机" :value="2" ></el-option>
                                    <el-option label="图片" :value="3" ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="标签" prop="label">
                                <el-input type="textarea" autosize v-model="formData.label"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="主机" prop="hostName" v-if="formData.type==1">
                <span>
                  <el-input style="width:400px;float: left" id="host" v-model="formData.hostName" disabled></el-input>
                  <el-button type="primary" plain @click="chooseHost">选择</el-button>
                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!--          交换机-->
                    <el-row>
                        <el-col>
                            <el-form-item label="交换机" prop="snmpName" v-if="formData.type==2">
                <span>
                  <el-input style="width:400px;float: left" id="snmpN" v-model="formData.snmpName" disabled></el-input>
                  <el-button type="primary" plain @click="chooseSNMP">选择</el-button>
                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="URL名称" prop="urlName">
                <span>
                  <el-input style="width:400px;float: left" v-model="formData.urlName"></el-input>
                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="URL" prop="url">
                <span>
                  <el-input style="width:400px;float: left" v-model="formData.url"></el-input>
                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="座标" prop="coordinate" >
                            <el-col :span="8">
                                <el-form-item label="X" prop="coordinateX" >
                  <span>
                  <el-input style="width:200px;float: left" v-model="formData.coordinateX"></el-input>
                  </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="Y" prop="coordinateY" >
                  <span>
                  <el-input style="width:200px;float: left" v-model="formData.coordinateY"></el-input>
                  </span>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </el-row>

                    <el-form-item>
                        <div style="margin: auto;float: right">
                            <el-button type="primary" @click="handleEdit('formData')">应 用</el-button>
                            <el-button @click="cancelEdit()">取 消</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <!-- 物理机选择弹窗 -->
        <el-dialog
                custom-class="tree-dialog-settings"
                title="选择物理机"
                :lock-scroll="false"
                :visible.sync="dialogEngineChooseVisible">
            <el-input
                    placeholder="输入查找主机名(区分大小写)"
                    v-model="filterText"
                    style="margin-top: 10px"
                    size="small">
            </el-input>
            <div style="overflow: auto;height: 300px;margin-top: 10px">
                <el-tree
                        :data="hostLists"
                        :props="defaultProps"
                        show-checkbox
                        node-key="id"
                        :filter-node-method="filterNode"
                        ref="tree">
                </el-tree>
            </div>
            <div style="flex-shrink: 0;margin-top:6px;text-align: right;">
                <el-button size="mini" @click="resetChecked">重置选择</el-button>
                <el-button type="primary" size="mini" @click="getCheckedNodes">确认选择</el-button>
                <el-button type="danger" size="mini" @click="dialogEngineChooseVisible=!dialogEngineChooseVisible">退出选择</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import TopoMenu from "@/views/topology/TopoMenu";
    import axios from 'axios'
    export default {
        name: "TopoMapEdit",
        data(){
            return{
                canvas: {},
                stage: {}, //舞台
                scene: {}, //场景
                engineRoomDetails:{},
                isEditFormShow: false,
                isGridShow: true,
                radioMode: 'drag',
                formData: {
                    type: 3,
                    label: '',
                    hostName: '',
                    snmpName: '',
                    hostID: '',
                    urlName: '',
                    url: '',
                    coordinateX:'',
                    coordinateY:'',
                },
                canvasWidth: document.body.clientWidth*0.746,
                canvasHeight: document.body.clientHeight*0.746,
                dialogEngineChooseVisible: false,
                hostLists: [{
                    label: '主机',
                    children: [],
                }, {
                    label: '交换机',
                    children: []
                }],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                currentChooseHost: [],
                nodeContent: [], // 临时存放关于节点的一些内容
                filterText: '',
                activeName: 'first',
                nodeIdIndex: [],// 保存节点selementid信息,
                showNumber: 1,
                hostElementVisable: true,
                wordElementVisable: false,
                imgSrc: null,
                imgLabel: ''
            }
        },
        components: {
          TopoMenu,
        },
        methods:{
            // 开始拖动
            dragStart(event){
                // console.log(event);
                // console.log("拖动开始")
                event.dataTransfer.setData("imgSrc", event.target.firstChild.currentSrc);
                event.dataTransfer.setData("imgLabel", event.target.innerText);
            },

            // 正在拖动
            allowDrop(event){
                event.preventDefault();
                // console.log("拖动")
            },

            // 拖动完成
            drop(event){
                event.preventDefault();
                // console.log(event);
                // console.log("拖动完成")
                // console.log(event.dataTransfer.getData("imgSrc"));
                // console.log(event.dataTransfer.getData("imgLabel"));
                this.imgSrc = event.dataTransfer.getData("imgSrc")
                this.imgLabel = event.dataTransfer.getData("imgLabel")
            },
            // 元素选择库切换
            elementChooseChange(){
                this.hostElementVisable = !this.hostElementVisable
                this.wordElementVisable = !this.wordElementVisable
            },

            // 根据拓扑图sysmapids获取拓扑图内容，并绘制拓扑图
            async paintTopoMapBySysmapids(sysmapids) {
                let mapParams = {}
                await axios.get('map/getMapBySysmapids.action', {
                    params: {
                        sysmapids: sysmapids
                    }
                }).then((res) => {
                    // console.log(res.data.content.result[0]);
                    mapParams = res.data.content.result[0]
                })
                // 清空当前画布
                if (this.scene.getDisplayedElements().length !== 0) {
                    // console.log(this.scene.getDisplayedElements());
                    this.deleteElements(this.scene.getDisplayedElements())
                }
                // 创建节点并进行连线
                // console.log(mapParams);
                let Node = null
                for (let i = 0; i < mapParams.selements.length; i++) {
                    Node = this.addNode(mapParams.selements[i].label, null, mapParams.selements[i].selementid)
                    Node.setLocation(parseInt(mapParams.selements[i].x), parseInt(mapParams.selements[i].y))
                }

                let currentNodeList = this.scene.getDisplayedElements()
                // console.log(currentNodeList);
                let nameList = []
                let nodeList = []
                for (let i = 0; i < mapParams.links.length; i++) {
                    // 遍历索引看该节点是否存在，存在则获得其Node对象并连线
                    nameList = []
                    mapParams.selements.forEach((node)=>{
                        if(node.selementid === mapParams.links[i].selementid1 || node.selementid === mapParams.links[i].selementid2){
                            nameList.push(node.label)
                        }
                        if(nameList.length === 2){
                            return 0
                        }
                    })
                    nodeList = []
                    currentNodeList.forEach((item)=>{
                        if(item.text === nameList[0] || item.text === nameList[1]){
                            nodeList.push(item)
                        }
                        if(nodeList.length === 2){
                            return 0
                        }
                    })
                    this.addLink(nodeList[0],nodeList[1])

                }
            },

            // 保存拓扑图至数据库
            saveTopu(){
                // console.log(this.nodeIdIndex);
                var selements = []
                var links = []
                if(this.scene.getDisplayedElements().length !== 0){
                    let elements = this.scene.getDisplayedElements()

                    let element = {}
                    let link = {}
                    for (let i = 0; i < elements.length; i++) {
                        element = {}
                        link = {}
                        if(elements[i] instanceof JTopo.Node){// 封装主机元素
                            // 获取当前Node对应主机的hostid
                            let hostid = ""
                            for (let j = 0; j < this.nodeContent.length; j++) {
                                for(let key in this.nodeContent[j]){
                                    if(key === "host" && this.nodeContent[j][key] === elements[i].text){
                                        hostid = this.nodeContent[j]["hostid"]
                                        break;
                                    }
                                }
                                if(hostid !== ""){
                                    break;
                                }
                            }
                            element = {
                                "elements": [
                                    {"hostid": hostid}
                                ],
                                "elementtype": 0,
                                "selementid": elements[i].text.concat(elements[i]._id.substr(-4)),// 保证唯一性
                                "iconid_off": 151,
                                "label": elements[i].text,
                                "x": Math.round(elements[i].x),
                                "y": Math.round(elements[i].y)
                            }
                            selements.push(element)
                        }else if(elements[i] instanceof JTopo.Link){// 封装线元素
                            // 获取连线两端两个节点的selementid
                            let selementid1 = ""
                            let selementid2 = ""
                            this.nodeIdIndex.forEach((item)=>{
                                if(item.host === elements[i].nodeA.text){
                                    selementid1 = item.selementid
                                } else if(item.host === elements[i].nodeZ.text){
                                    selementid2 = item.selementid
                                }
                                if(selementid1 !== "" && selementid2 !== ""){
                                    return;
                                }
                            })
                            link = {
                                "selementid1": selementid1,
                                "selementid2": selementid2,
                                "color": "10,204,80",
                            }
                            links.push(link)
                        }
                    }
                    // console.log(selements);
                    // console.log(links);
                    let grid_show = 0;// 0-显示，1-不显示
                    if(!this.isGridShow){
                        grid_show = 1
                    }
                    let topoMapParams = {
                        "name": "topology"+Math.round(Math.random()*100),
                        "width": this.canvasWidth,
                        "height": this.canvasHeight,
                        "grid_show": grid_show,
                        "selements": selements,
                        "links": links
                    }
                    // console.log(topoMapParams);
                    // topoMapParams = JSON.stringify(topoMapParams)
                    this.$axios({
                        method: "POST",
                        url:"map/createMap.action",
                        data: topoMapParams
                    }).then((response)=> {
                        // console.log(response);
                        if(response.data.content === null){
                            this.$message.error(response.data.errorCode);
                        }else {
                            this.$message({
                                message: '拓扑图保存成功',
                                duration: 2000,
                                type: 'success'
                            })
                        }
                    }).catch((error)=>{
                        this.$message({
                            message: '拓扑图保存失败',
                            duration: 2000,
                            type: 'warning'
                        })
                    })
                }else{
                    this.$message({
                        message: '未检测到拓扑图元素',
                        duration: 2000,
                        type: 'warning'
                    })
                }
            },

            // 视图切换
            handleClick(tab,event){
                console.log(tab, event);
                if (tab.name == 'first'){
                    this.showNumber = 1
                }
                else if (tab.name == 'second'){
                    this.showNumber = 2
                }
                else{
                    this.showNumber = 3
                }
                // alert(tab.label)
            },

            // 初始化拓扑图
            topoInitCreate(){
                if(this.currentChooseHost.length === 0){// 判断物理机是否选择
                    this.$notify({
                        title: '请确认物理机是否选择',
                        duration: 2000,
                        type: 'warning',
                        offset: -1
                    });
                }else{
                    this.$notify({
                        title: '拓扑图初始化中...',
                        duration: 2000,
                        type: 'success',
                        offset: -1
                    });
                    // console.log(this.currentChooseHost);
                    this.initTreeLayout(this.currentChooseHost)
                }
            },

            // 获得弹窗中选择的树形节点
            getCheckedNodes(){
                this.currentChooseHost = this.$refs.tree.getCheckedNodes()
                this.dialogEngineChooseVisible = false
            },

            // 对树形节点进行清空重置
            resetChecked() {
                this.$refs.tree.setCheckedKeys([]);
            },

            // 对树形节点进行过滤选择
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },

            // 选择物理机
            chooseEngines(){
                this.findAllHosts()
                this.dialogEngineChooseVisible = true
            },

            // 获取当前所有主机
            findAllHosts(){
                axios.get('/host/findAllHost.action').then((res) => {
                    // console.log(res);
                    this.hostLists[0].children = []
                    this.hostLists[1].children = []
                    for(let i = 0;i < res.data.content.hosts.length;i++) {
                        if (res.data.content.hosts[i].snmp_available === '0') {
                            this.hostLists[0].children.push({"id": i, "label": res.data.content.hosts[i].host})
                        } else {
                            this.hostLists[1].children.push({"id": i, "label": res.data.content.hosts[i].host})
                        }
                    }
                    // 保存主机相关信息,以备他用
                    this.nodeContent = res.data.content.hosts
                    // console.log(this.nodeContent);
                })
            },

            // 初始化节点树形布局
            initTreeLayout(val){
                var rootNode = this.addNode(val[0].label, 'gray');
                rootNode.setLocation(360,130);

                for(var i=1; i < val.length; i++){
                    var node = this.addNode(val[i].label, null);
                    this.addLink(rootNode, node);

                    // if(i == 0 || i == 3){
                    //     for(var j=0; j<4; j++){
                    //         var thirdNode = this.addNode('third_' + j, 'green');
                    //         this.addLink(node, thirdNode);
                    //         if(j == 3){
                    //             for(var k=0; k<4; k++){
                    //                 var kNode = this.addNode('leaf_' + k, 'gray');
                    //                 this.addLink(thirdNode, kNode);
                    //             }
                    //         }
                    //     }
                    // }
                }
                // 树形布局
                this.scene.doLayout(JTopo.layout.TreeLayout('down', 100, 130));

            },

            addNode(text, color,selementid){
                let node = new JTopo.Node(text);
                node.setSize(Math.round(parseFloat(this.canvasWidth)*0.01)*4,Math.round(parseFloat(this.canvasWidth)*0.01)*3)// 依据当前画布大小确定图标元素大小
                node.setImage(require("../../../public/img/topo/picture.png"))
                node.fontColor = '0,0,0'; // 文字颜色
                node.shadow = true // 显示阴影

                // this.addNotice(node,'Warrning','255,0,0')

                this.scene.add(node);
                // node.mouseover(function(){
                //     this.text = text;
                // });
                // node.mouseout(function(){
                //     this.text = null;
                // });
                // 绑定双击编辑
                node.dbclick((e)=>{
                    this.editNode(e)
                });

                // 保存其selementid信息,若已经保存过则更新
                // console.log(selementid);
                let flag = false
                for (let i = 0; i < this.nodeIdIndex.length; i++) {
                    if(this.nodeIdIndex[i].host === text){
                        this.nodeIdIndex[i].host = selementid
                        flag = true
                        break
                    }
                }
                if(!flag){
                    this.nodeIdIndex.push({
                        "host": text,
                        "selementid": text.concat(node._id.substr(-4))
                    })
                }
                return node;
            },

            /*
                添加提示
                node: 节点对象
                text: 提示信息
                color: 提示颜色
             */
            addNotice(node,text,color){
                node.alarm = text;
                node.alarmColor = color;
                node.alarmAlpha = 0.9;
            },

            addLink(nodeA, nodeZ){
                var link = new JTopo.FlexionalLink(nodeA, nodeZ);
                link.direction = 'vertical'
                link.strokeColor = '164,176,190'
                link.lineWidth = 1.5;
                this.scene.add(link);
                return link;
            },

            //添加线
            createLink(){
                //获取场景中选中的元素
                let selected = this.scene.selectedElements
                let nodes = []
                let j=0
                for (let i = 0; i < selected.length; i++) {
                    if(selected[i] instanceof JTopo.Node && selected[i].width > 0){
                        nodes[j++] = selected[i]
                    }
                }
                if(j >= 2){
                    let link = this.addLink(nodes[0], nodes[1]);
                    //记录连线索引
                    this.linkIdIndex.push(link._id.substr(-4))
                    this.isChangedFlag = true
                }else{
                    this.$message({
                        message: '请选择要连线的两个节点',
                        type: 'warning'
                    })
                }
            },

            // 编辑节点
            editNode(){
                this.isEditFormShow = true
            },

            // 动态连接两个节点
            createLinkdynamic(){
                // 动态连线初始化准备
                var beginNode = null;
                var tempNodeA = new JTopo.Node('tempA');
                tempNodeA.setSize(1, 1);
                var tempNodeZ = new JTopo.Node('tempZ');
                tempNodeZ.setSize(1, 1);
                var link = new JTopo.Link(tempNodeA, tempNodeZ);
                link.strokeColor = '201,201,211';
                link.lineWidth = 1.5; // 线宽

                // 连线跟随鼠标移动
                this.scene.mousemove(function(e){
                    tempNodeZ.setLocation(e.x, e.y);
                });

                this.scene.mousedown(e => {
                    if(e.target == null || e.target === beginNode || e.target === link){
                        this.scene.remove(link);
                    }
                });

                this.scene.mouseup(e => {
                    // 右键取消正在进行的连线
                    if(e.button == 2){
                        this.scene.remove(link);
                        return;
                    }
                    if(e.target != null && e.target instanceof JTopo.Node){
                        if(beginNode == null){
                            beginNode = e.target;
                            this.scene.add(link);
                            tempNodeA.setLocation(e.x, e.y);
                            tempNodeZ.setLocation(e.x, e.y);
                        }else if(beginNode !== e.target){
                            var endNode = e.target;

                            var l = new JTopo.Link(beginNode, endNode);
                            l.strokeColor = '201,201,211';
                            l.lineWidth = 1.5; // 线宽

                            this.scene.add(l);
                            beginNode = null;
                            this.scene.remove(link);
                        }else{
                            beginNode = null;
                        }
                    }else{
                        this.scene.remove(link);
                    }
                });
            },

            // 初始化操作
            init(){
                this.canvas = document.getElementById("canvas")
                this.stage = new JTopo.Stage(canvas);
                this.scene = new JTopo.Scene(this.stage);
                // 拖拽图标到场景并松开鼠标
                this.stage.mouseover((e)=> {
                    if (null !== this.imgSrc) {
                        let node = this.addNode(this.imgLabel)
                        node.setImage(this.imgSrc, true);
                        node.setSize(Math.round(parseFloat(this.canvasWidth)*0.01)*4,Math.round(parseFloat(this.canvasWidth)*0.01)*3)
                        node.setLocation(e.x,e.y);
                        this.imgSrc = null;
                    }
                });
            },

            // 创建节点
            createNode() {
                var node = this.addNode("测试节点")
                node.setLocation(Math.random() * this.canvasWidth, Math.random() * this.canvasHeight);
            },

            // 删除选中节点
            deleteChooseNode(){
                this.deleteElements(this.scene.selectedElements)
            },

            // 删除元素
            deleteElements(Elements){
                if(Elements !== null && Elements.length !== 0){
                    for(let i = 0; i < Elements.length; i++){
                        this.scene.remove(Elements[i])
                    }
                }
            },

            // 返回机房列表页面
            back(){
                this.$router.push('/topoCabinet/'+this.engineRoomDetails.currentEngineRoom+'/'+this.engineRoomDetails.currentRoomNo)
            },
            //切换事件
            change(index){
              this.showNumber = index
              console.log(index)
            },
            // 红色暴炸
            redBoom(){
                // 清空当前画布
                if (this.scene.getDisplayedElements().length !== 0) {
                    // console.log(this.scene.getDisplayedElements());
                    this.deleteElements(this.scene.getDisplayedElements())
                }
                for (let i = 0; i < 200; i++) {
                    this.createNode()
                }
            }
        },

        mounted() {
            this.init()
            this.createLinkdynamic()
            this.engineRoomDetails = this.$route.query
            // console.log(this.$route.query)
            // this.initTreeLayout()
        },
        watch: {
            //监听鼠标选项变化
            radioMode(newMode, oldMode) {
                this.stage.mode = newMode
            },
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
    }
</script>

<style scoped>
    .mapedit{
        height: 100%;
        width: 100%;
        background-color: #F0F2F5;
        position: absolute;
    }
    .topoContent {
        display: flex;
        margin-top: 60px;
        height: 92%;
        width: 100%;
    }
    .mapedit-main{
        height: 100%;
        width: 100%;
        margin-top: 0;
        padding:10px;
    }
    .map-left-content {
        height: 97%;
        overflow-x:hidden
    }
    .map-left-content-bottom{
        height:3%;
        background-color: #F0F2F5;
        text-align: center;
    }
    /*<!-- 主内容-上部分  -->*/
    .left_head{
        width: 100%;
    }
    /*<!-- 主内容-上部分-标题栏  -->*/
    .left_head_title {
        background-color: #f3eded;
        width: 100%;
        height: 38px;
    }
    /*<!-- 主内容-上部分-视图切换栏  -->*/
    .left-head-views{
        background-color: white;
        width: 100%;
        height: 38px;
    }
    /*<!-- 主内容-上部分-工具栏  -->*/
    .left_head_tool {
        background-color: #C9C9D3;
        width: 100%;
        height: 40px;
    }
    /*<!-- 主内容-下部分  -->*/
    .map_body {
        display: flex;
        width: 100%;
        height: 86%;
    }
    /*<!-- 主内容-下部分-更左边机房机柜展示列表  -->*/
    .map-body-lefter-room{
        background-color: white;
        width: 15%;
        height: 100%;
    }
    /*<!-- 主内容-下部分-左边拓扑图内容  -->*/
    .map_body_left {
        background-color: white;
        width: 85%;
        height: 100%;
    }
    /*右侧菜单栏*/
    .right_menu {
      max-height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
    }
    .el_divider{
        margin: 4px 0 !important;
    }
    .divelement:hover{
        background-color: whitesmoke;
        cursor: move;
        /*transition: all 0.8s ease;*/
    }
    .mapCanvas-content {
        background-image: linear-gradient(90deg, rgba(50, 0, 0, 0.1) 2%, rgba(0, 0, 0, 0) 2%), linear-gradient(360deg, rgba(50, 0, 0, 0.1) 2%, rgba(0, 0, 0, 0) 2%);
        background-size: 25px 25px;
        background-repeat: repeat;
        background-position: center center;
    }
    .el-tree {
        min-width: 100%;
        display: inline-block;
    }
    .el-dialog__body {
        padding: 0;
    }

</style>
<style>
    .tree-dialog-settings {
        background-color: #F0F2F5;
        height: 60%;
        width: 30%;
    }
    .el-dialog__body {
        padding-top: 0px;
    }
    .el-checkbox:last-of-type {
        margin-right: 8px;
        margin-bottom: 0px;
    }
    .el-tabs__item{
        padding-left: 20px !important;
    }
</style>